package com.usian.common;


import com.usian.pojo.Result;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class UploadController {

    @Value("${reggie.path}")
    private String path;

    @PostMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + suffix;
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        File dirPath = new File(dir,newFileName);
        file.transferTo(dirPath);
        return Result.success(newFileName);
    }


    @GetMapping("download")
    public void download(String name , HttpServletResponse response) throws IOException {
        File file = new File(path,name);
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buf = new byte[1024];
        int length =0;
        //边读边写
        while((length=fileInputStream.read(buf))!=-1){
            outputStream.write(buf,0,length);
        }
        fileInputStream.close();
    }

}
